package com.xinchili.mysqlSimulateRedis.service.impl;

import java.util.concurrent.*;
import com.xinchili.mysqlSimulateRedis.service.RedisService;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;

//@Service
public class RedisCacheService implements RedisService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


//    // 如果需要配置 RedisTemplate，建议将此方法移到配置类中并添加 @Bean 注解
//    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
//        //创建Redis模板对象
//        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
//        //设置连接
//        template.setConnectionFactory(factory);
//        // 配置JSON序列化器
//        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//        ObjectMapper om = new ObjectMapper();
//        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//        jackson2JsonRedisSerializer.setObjectMapper(om);
//        // 配置字符串序列化器
//        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//        // key采用String的序列化方式
//        template.setKeySerializer(stringRedisSerializer);
//        // hash的key也采用String的序列化方式
//        template.setHashKeySerializer(stringRedisSerializer);
//        // value序列化方式采用jackson
//        template.setValueSerializer(jackson2JsonRedisSerializer);
//        // hash的value序列化方式采用jackson序列化器
//        template.setHashValueSerializer(jackson2JsonRedisSerializer);
//        // 完成配置
//        template.afterPropertiesSet();
//        return template;
//    }

    @Override
    public void set(String key, String value, long expire) {
        try {
            if (expire > 0) {
                redisTemplate.opsForValue().set(key, value);
                redisTemplate.expire(key, expire, TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().set(key, value);
            }
            System.out.println("Set operation completed");
        } catch (Exception e) {
            System.err.println("Error setting key: " + e.getMessage());
            e.printStackTrace();
        }
    }



    @Override
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public String get(String key) {
        Object result = redisTemplate.opsForValue().get(key);
        return result != null ? result.toString() : null;
    }

    @Override
    public void delete(String key) {
        redisTemplate.delete(key);
    }
}
